/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.controller.company;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.je.common.base.DynaBean;
import com.je.common.base.controller.CommonTreeController;
import com.je.common.base.exception.PlatformException;
import com.je.common.base.exception.PlatformExceptionEnum;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.result.DirectJsonResult;
import com.je.common.base.service.CommonTreeService;
import com.je.core.entity.extjs.JSONTreeNode;
import com.je.ibatis.extension.plugins.pagination.Page;
import com.je.rbac.annotation.ControllerAuditLog;
import com.je.rbac.exception.AccountException;
import com.je.rbac.exception.DepartmentException;
import com.je.rbac.exception.DepartmentUserException;
import com.je.rbac.service.company.RbacDepartmentService;
import com.je.rbac.service.company.RbacDepartmentUserService;
import com.je.rbac.service.remove.CompanyDeptMoveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 部门管理
 */
@RestController
@RequestMapping(value = "/je/rbac/cloud/department")
public class RbacDepartmentController extends CommonTreeController {

    @Autowired
    private RbacDepartmentService rbacDepartmentService;
    @Autowired
    private RbacDepartmentUserService rbacDepartmentUserService;
    @Autowired
    private CommonTreeService commonTreeService;
    @Autowired
    private CompanyDeptMoveService companyDeptMoveService;

    /***
     * 加载部门列表
     * @param param
     * @param request
     * @return
     */
    @Override
    @RequestMapping( value = {"/load"}, method = {RequestMethod.POST}, produces = {"application/json; charset=utf-8"})
    @ControllerAuditLog(moduleName = "部门管理", operateTypeCode = "loadDepartment", operateTypeName = "查看部门", logTypeCode = "systemManage", logTypeName = "系统管理")
    public BaseRespResult load(BaseMethodArgument param, HttpServletRequest request) {
        rbacDepartmentUserService.loadParam(param);
        Page page = this.manager.load(param, request);
        return page == null ? BaseRespResult.successResultPage(Lists.newArrayList(), 0L) : BaseRespResult.successResultPage(page.getRecords(), (long)page.getTotal());
    }

    /***
     * 保存
     * @param param
     * @param request
     * @return
     * @throws DepartmentUserException
     */
    @Override
    @RequestMapping(value = "/doSave", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "部门管理", operateTypeCode = "saveDepartment", operateTypeName = "保存部门", logTypeCode = "systemManage", logTypeName = "系统管理")
    public BaseRespResult doSave(BaseMethodArgument param, HttpServletRequest request) throws DepartmentUserException{
            //获取新增数据
            String parentNodetype = getStringParameter(request, "PARENT_NODETYPE");

            String syParent = getStringParameter(request, "SY_PARENT");

            // 获取新增数据
            DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
            dynaBean.setStr("PARENT_NODETYPE",parentNodetype);
            dynaBean.setStr("SY_PARENT",syParent);
            if(!rbacDepartmentService.checkDeptCodeUnique(dynaBean)){
                return BaseRespResult.errorResult("组织编码重复，请修改！");
            }
        try {
            DynaBean savedBean = rbacDepartmentService.doSave(dynaBean);
            JSONTreeNode node = commonTreeService.buildSingleTreeNode(savedBean);
            Map<String, Object> result = new HashMap<>();
            result.put("dynaBean", savedBean.getValues());
            result.put("node", node);
            return BaseRespResult.successResult(result);
        } catch (DepartmentUserException e) {
            return BaseRespResult.errorResult(e.getMessage());
        }
    }

    /***
     * 修改
     * @param param
     * @param request
     * @return
     * @throws DepartmentUserException
     */
    @Override
    @RequestMapping(value = "/doUpdate", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "部门管理", operateTypeCode = "updateDepartment", operateTypeName = "查看部门", logTypeCode = "systemManage", logTypeName = "系统管理")
    public BaseRespResult doUpdate(BaseMethodArgument param, HttpServletRequest request){
            //获取修改数据
            DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
            if(!rbacDepartmentService.checkDeptCodeUnique(dynaBean)){
                return BaseRespResult.errorResult("组织编码重复，请修改！");
            }
        try {
            DynaBean sourceDeptBean = rbacDepartmentService.findById(dynaBean.getStr("JE_RBAC_DEPARTMENT_ID"));
            rbacDepartmentService.updateDeptName(dynaBean);
            DynaBean updatedBean = manager.doUpdate(param, request);

            //验证若所属公司，部门 发生修改则移动该部门，并同步修改部门下级，树形数据，公司，集团数据
            rbacDepartmentService.checkAndMoveDeptCompanyInfo(sourceDeptBean,dynaBean);

            rbacDepartmentService.updateSyncMajorUser(updatedBean);
            JSONTreeNode node = commonTreeService.buildSingleTreeNode(updatedBean);
            Map<String, Object> result = new HashMap<>();
            result.put("dynaBean", updatedBean.getValues());
            result.put("node", node);
            return BaseRespResult.successResult(result);
        } catch (DepartmentException e) {
            return BaseRespResult.errorResult(e.getMessage());
        }
    }

    /**
     * 重置密码
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"/userResetPassword"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "部门管理", operateTypeCode = "resetDepartmentUser", operateTypeName = "重置部门人员密码", logTypeCode = "systemManage", logTypeName = "系统管理")
    public BaseRespResult userResetPassword(HttpServletRequest request) throws AccountException, DepartmentUserException {
        String userIds = getStringParameter(request, "userIds");
        if (Strings.isNullOrEmpty(userIds)) {
            return BaseRespResult.errorResult("请选择人员！");
        }
        long count = rbacDepartmentUserService.userResetPassword(userIds);
        if(count<=0){
            return BaseRespResult.errorResult("重置密码失败"+count+"条人员信息！");
        }
        return BaseRespResult.successResult("重置密码成功！");
    }



    /**
     * 启用
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"/enable"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "部门管理", operateTypeCode = "enableDepartment", operateTypeName = "启用部门", logTypeCode = "systemManage", logTypeName = "系统管理")
    public BaseRespResult enable(HttpServletRequest request) {
        String departmentIds = getStringParameter(request, "departmentIds");
        if (Strings.isNullOrEmpty(departmentIds)) {
            return BaseRespResult.errorResult("请选择需要启用的部门！");
        }
        try{
            //判断上级部门是否启用，若部门上级节点为root 则判断所属公司是否禁用
            if(rbacDepartmentService.findUpCompanyStatus(departmentIds) && rbacDepartmentService.findUpDeptStatus(departmentIds)){
                rbacDepartmentService.enableDepartments(departmentIds);
            }
        }catch (DepartmentException e){
            return BaseRespResult.errorResult(e.getMessage());
        }
        return BaseRespResult.successResult("启用成功！");
    }

    /**
     * 禁用
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"/disable"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "部门管理", operateTypeCode = "disableDepartment", operateTypeName = "禁用部门", logTypeCode = "systemManage", logTypeName = "系统管理")
    public BaseRespResult disable(HttpServletRequest request) {
        String departmentIds = getStringParameter(request, "departmentIds");
        if (Strings.isNullOrEmpty(departmentIds)) {
            return BaseRespResult.errorResult("请选择需要禁用的部门！");
        }
        rbacDepartmentService.disableDepartments(departmentIds);
        return BaseRespResult.successResult("禁用成功！");
    }

    /**
     * 删除
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"/remove"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "部门管理", operateTypeCode = "removeDepartment", operateTypeName = "移除部门", logTypeCode = "systemManage", logTypeName = "系统管理")
    public BaseRespResult remove(BaseMethodArgument param, HttpServletRequest request) throws DepartmentUserException {
        String ids = getStringParameter(request, "ids");
        String withUsers = getStringParameter(request, "withType");
        if (Strings.isNullOrEmpty(ids)) {
            return BaseRespResult.errorResult("请选择要删除的部门！");
        }
        if("0".equals(withUsers) && !rbacDepartmentService.checkChildDept(ids)){
            return BaseRespResult.errorResult("该部门存在下级部门，不允许删除！");
        }
        if("0".equals(withUsers) && !rbacDepartmentService.checkChildUser(ids)){
            return BaseRespResult.errorResult("该部门存在员工，不允许删除！");
        }
        long count = rbacDepartmentService.removeDepartments(ids, "1".equals(withUsers));
        if(count<=0){
            return BaseRespResult.errorResult("删除失败！");
        }
        return BaseRespResult.successResult("操作成功");
    }


    /**
     * 移除部门人员
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"/removeUser"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "部门管理", operateTypeCode = "removeDepartmentUser", operateTypeName = "移除部门人员", logTypeCode = "systemManage", logTypeName = "系统管理")
    public BaseRespResult removeUser(BaseMethodArgument param, HttpServletRequest request){
        String userDeptIds = getStringParameter(request, "userDeptIds");
        if(Strings.isNullOrEmpty(userDeptIds)){
            return BaseRespResult.errorResult("请选择部门或人员！");
        }
        try{
            rbacDepartmentService.removeDepartmentUser(userDeptIds);
        }catch (Exception e){
            return BaseRespResult.errorResult(e.getMessage());
        }
        return BaseRespResult.successResult("操作成功");
    }

    @RequestMapping(
            value = {"/getTree"},
            method = {RequestMethod.POST},
            produces = {"application/json; charset=utf-8"}
    )
    @Override
    public BaseRespResult getTree(BaseMethodArgument param, HttpServletRequest request) {
        try {
            JSONTreeNode tree= rbacDepartmentService.buildCompanyTreeData(true);
            return tree != null ? BaseRespResult.successResult(DirectJsonResult.buildObjectResult(tree)) : BaseRespResult.successResult(DirectJsonResult.buildObjectResult("{}"));
        } catch (PlatformException var4) {
            throw var4;
        } catch (Exception var5) {
            throw new PlatformException("数据加载失败！", PlatformExceptionEnum.UNKOWN_ERROR, var5);
        }
    }


    /**
     * 导入已有员工同时在本部门任职
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"/addToOwnDepartment"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "部门管理", operateTypeCode = "imortDepartmentUser", operateTypeName = "导入已有部门员工在本部门任职", logTypeCode = "systemManage", logTypeName = "系统管理")
    public BaseRespResult addToOtherDepartment(HttpServletRequest request) {
        String departmentId = getStringParameter(request,"departmentId");
        String userIds = getStringParameter(request,"userIds");
        if(Strings.isNullOrEmpty(departmentId)){
            return BaseRespResult.errorResult("请先保存主功能！");
        }
        if(Strings.isNullOrEmpty(userIds)){
            return BaseRespResult.errorResult("请选择要添加的人员！");
        }

        try {
            rbacDepartmentService.addOwnDepartment(departmentId,userIds);
        }catch (DepartmentUserException e){
            return BaseRespResult.errorResult(e.getMessage());
        }

        return BaseRespResult.successResult("操作成功");
    }

    /**
     * 查询部门树
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"/loadDepartmentTree"}, method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public BaseRespResult loadDepartmentTree(HttpServletRequest request) {
        String companyIds = getStringParameter(request,"companyIds");
        JSONTreeNode rootNode;
        if(Strings.isNullOrEmpty(companyIds)){
            rootNode = rbacDepartmentService.buildCompanyTreeData(true);
        }else {
            rootNode = rbacDepartmentService.buildCompanyTreeData(true,companyIds.split(","));
        }
        return BaseRespResult.successResult(rootNode);
    }

    @RequestMapping(value = {"/moveDepartMent"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "部门管理", operateTypeCode = "moveDepartment", operateTypeName = "移动部门", logTypeCode = "systemManage", logTypeName = "系统管理")
    public BaseRespResult moveDepartMent(HttpServletRequest request){
        String tableCode = getStringParameter(request, "tableCode");
        if (Strings.isNullOrEmpty(tableCode)) {
            return BaseRespResult.errorResult("请选择要移动数据的表编码！");
        }
        String id = getStringParameter(request, "id");
        if (Strings.isNullOrEmpty(id)) {
            return BaseRespResult.errorResult("请选择要移动的数据！");
        }
        String toId = getStringParameter(request, "toId");
        if (Strings.isNullOrEmpty(toId)) {
            return BaseRespResult.errorResult("请选择要移动的目标数据！");
        }
        String place = getStringParameter(request, "place");
        if (Strings.isNullOrEmpty(place)) {
            return BaseRespResult.errorResult("请选择要移动的数据位置！");
        }
        try {
            DynaBean dynaBean = new DynaBean("",false);
            dynaBean.put("id",id);
            dynaBean.put("toId",toId);
            dynaBean.put("place",place);
            companyDeptMoveService.move(dynaBean);
        } catch (DepartmentUserException e) {
            return BaseRespResult.errorResult(e.getMessage());
        }

        return BaseRespResult.successResult("操作成功！");
    }
}
